package com.example.hotel_lxy.ui.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.example.hotel_lxy.R;
import com.example.hotel_lxy.adapter.CustomAdapter;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.Cell;
import com.example.hotel_lxy.bean.ColTitle;
import com.example.hotel_lxy.bean.DataInfoBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.RowTitle;
import com.example.hotel_lxy.bean.ScheduledBean;
import com.example.hotel_lxy.bean.WHBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.activity.MainActivity;
import com.example.hotel_lxy.ui.activity.PotentialInformationActivity;
import com.example.hotel_lxy.ui.activity.ReserveActivity;
import com.example.hotel_lxy.ui.activity.ReserveInformationActivity;
import com.example.hotel_lxy.ui.activity.SwitchAccountsActivity;
import com.example.hotel_lxy.ui.activity.ZeroPointActivity;
import com.example.hotel_lxy.ui.dialog.HallListDialog;
import com.example.hotel_lxy.ui.dialog.HotleChoiceDialog;
import com.example.hotel_lxy.ui.main.CalendarActivity;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.DateUtils;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.google.gson.Gson;
import com.ysxsoft.common_base.base.BaseFragment;
import com.ysxsoft.common_base.base.BasePopupWindow;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;

import butterknife.BindView;
import cn.zhouchaoyuan.excelpanel.ExcelPanel;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.ysxsoft.common_base.base.BaseApplication.getContext;

/***
 *
 * 首页
 *
 */
public class FragmentHome extends BaseFragment implements ExcelPanel.OnLoadMoreListener {
    public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd";
    public static final String WEEK_FORMAT_PATTERN = "EEEE";

    public static final long ONE_DAY = 24 * 3600 * 1000;
    public static int PAGE_SIZE = 50;
    public static int ROW_SIZE = 30;


    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.tv_choice_hall)
    TextView tvChoiceHall;
    @BindView(R.id.tv_main_hotel)
    TextView tvMainHotel;
    @BindView(R.id.tv_main_time)
    TextView tvMainTime;
    @BindView(R.id.text_zero)
    TextView textZero;
    ScheduledBean scheduledBean;
    //        @BindView(R.id.content_container)
    ExcelPanel excelPanel;
    @BindView(R.id.frame_gr)
    FrameLayout frameGr;
    @BindView(R.id.line1)
    LinearLayout line1;
    @BindView(R.id.line_add_view)
    LinearLayout lineAddView;
    private boolean isLoading;
    private long historyStartTime;
    private long moreStartTime;
    DataInfoBean dataInfoBean;
    private CustomAdapter adapter;
    private List<RowTitle> rowTitles;
    private List<ColTitle> colTitles;
    private List<List<Cell>> cells;


    private SimpleDateFormat dateFormatPattern;
    private SimpleDateFormat weekFormatPattern;
    List<DataInfoBean.DataBean.ListBean> list;
    List<List<DataInfoBean.DataBean.ListBean>> mlist = new ArrayList<>();
    String banquet = "";
    String y = "";
    String m = "";
    String d = "";
    private List<String> DataList = new ArrayList<>();
    private ScaleGestureDetector mScaleGestureDetector = null;
    private List<WHBean> whList = new ArrayList<>();
    private float scale;
    private float preScale = 1;// 默认前一次缩放比例为1
    int leftCellWidth = 154;
    int topCellHeight = 82;
    int normalCellWidth = 154;
    private boolean aBoolean = true;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home_activity;
    }


    @Override
    protected void doWork(View view) {
//        PAGE_SIZE =DateUtils.getCurrentMonthLastDay();//
        String string1 = SPUtils.get(getContext(), "currentDate", "").toString();
        String[] two;
        two = string1.split("-");
        tvMainTime.setText(two[0] + "年" + two[1] + "月");
        y = two[0];
        m = two[1];
        d = two[2];
        DataList.add(y + "-" + m);
        initWhInfo();
        initListener();
        mScaleGestureDetector = new ScaleGestureDetector(getContext(),
                new ScaleGestureListener());
        ((MainActivity) this.getActivity()).registerMyTouchListener(myTouchListener);
        String string = SPUtils.get(getContext(), "hotel", "").toString();
        tvMainHotel.setText(string + "");
        Log.e("TAG", SPUtils.get(getContext(), "token", "").toString() + "   132");
    }

    private void initWhInfo() {
        WHBean whBean = new WHBean();
        whBean.setWeekHeight(83);
        whBean.setWeekWidth(127);
        whBean.setWeekSize(12);

        whBean.setRootheight(280);
        whBean.setRootwidth(127);
        whBean.setRootSize(12);

        whBean.setContainerheight(280);
        whBean.setContainerwidth(127);

        whBean.setPmswidth(127);
        whBean.setPmsheight(120);
        whBean.setTextSize(12);
        whBean.setBlow(6);
        whList.add(whBean);
    }

    private void ShowData(final String y, final String m, final String d, final int q) {
        Log.e("TAG",banquet+"");
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("year", "" + y)
                .add("month", "" + m)
                .add("banquet", banquet)
                .build();
        Request request = new Request.Builder()
                .url("http://lxy.yskxfs.com/api/Index/index")
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                showResponse(responseData, y, m, d, q);
            }
        });
    }

    private void showResponse(final String responseData, final String y, final String m, final String d, final int q) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void run() {
                Log.e("TAG", "run: " + responseData);
                dataInfoBean = new Gson().fromJson(responseData, DataInfoBean.class);
                BeanBean codeBean = new Gson().fromJson(responseData, BeanBean.class);
                if (codeBean.getCode().equals("0")) {
                    list = dataInfoBean.getData().getList();
                    mlist.add(list);
                    if (list.size() != 0) {
                        ROW_SIZE = list.size();
                    }
                    if (q == 3) {
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }
                    } else {

                        if (list.size() != 0) {
                            lineAddView.removeAllViews();
                            View views = LinearLayout.inflate(getContext(), R.layout.add_home_view, null);
                            views.setTag(lineAddView.getChildCount());//设置标记
                            initFind(views);
                            views.setPadding(0, 0, 0, 0);
                            lineAddView.addView(views);
                        }
                    }
                }else if (codeBean.getCode().equals("4")) {
                    Intent intent = new Intent(getContext(), LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

    private void initFind(View views) {
        excelPanel = views.findViewById(R.id.content_container);
        excelPanel.setOnLoadMoreListener(this);
        excelPanel.addOnScrollListener(onScrollListener);
        adapter = new CustomAdapter(getActivity(), blockListener, mlist, blockListenernoon, 1);
        excelPanel.setAdapter(adapter);
        adapter.setSf(whList, 1);
        initData(y + "-" + m + "-" + d);

    }

    private void loadData(long startTime, final boolean history) {
        //模拟网络加载
        isLoading = true;
        Message message = new Message();
        message.arg1 = history ? 1 : 2;
        message.obj = new Long(startTime);
        loadDataHandler.sendMessageDelayed(message, 0);
    }


    private Handler loadDataHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            isLoading = false;
            long startTime = (Long) msg.obj;
            List<RowTitle> rowTitles1 = genRowData(startTime);
            List<List<Cell>> cells1 = genCellData();

            if (msg.arg1 == 1) {//history
                historyStartTime -= ONE_DAY * PAGE_SIZE;
                rowTitles.addAll(0, rowTitles1);
                for (int i = 0; i < cells1.size(); i++) {
                    cells.get(i).addAll(0, cells1.get(i));
                }

                //加载了数据之后偏移到上一个位置去
                if (excelPanel != null) {
                    excelPanel.addHistorySize(PAGE_SIZE);
                }
            } else {
                moreStartTime += ONE_DAY * PAGE_SIZE;
                rowTitles.addAll(rowTitles1);
                for (int i = 0; i < cells1.size(); i++) {
                    cells.get(i).addAll(cells1.get(i));
                }
            }
            if (colTitles.size() == 0) {
                colTitles.addAll(genColData());
            }
            if (adapter == null) {
                return;
            }
            adapter.setAllData(colTitles, rowTitles, cells);
            adapter.enableFooter();
            adapter.enableHeader();
        }
    };


    public List<RowTitle> removeDuplicateWithOrder(List<RowTitle> list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;
    }

    private void initData(String data) {
        moreStartTime = dateStamp(data);
        historyStartTime = moreStartTime - ONE_DAY * PAGE_SIZE;
        dateFormatPattern = new SimpleDateFormat(DATE_FORMAT_PATTERN);
        weekFormatPattern = new SimpleDateFormat(WEEK_FORMAT_PATTERN);
        rowTitles = new ArrayList<>();
        colTitles = new ArrayList<>();
        cells = new ArrayList<>();

        for (int i = 0; i < ROW_SIZE; i++) {
            cells.add(new ArrayList<Cell>());
        }
        loadData(moreStartTime, false);

    }

    public static long dateStamp(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return ts;
    }

    private View.OnClickListener blockListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String xiaokongbiao = SPUtils.get(getContext(), "xiaokongbiao", "").toString();
            if (xiaokongbiao.equals("1")) {
                ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                return;
            }
            String string = view.getTag().toString();
            String[] split = string.split("/");
            Log.e("TAG", "上   " + split[0] + "  " + split[1] + "  " + split[2] + "  ");
            if (split[0].equals("NULL")) {
                long l = DatePhotoUtils.dateStamp(split[1]);
                DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date(System.currentTimeMillis());//获取当前时间
                String currentDate = simpleDateFormat.format(date);
                long l1 = DatePhotoUtils.dateStamp(currentDate);
                if (l < l1) {
                    ToastUtils.shortToast(getContext(), "禁止选择之前日期");
                } else {
                    boolean addscheduled = JurisdictionUtils.getAddscheduled(getContext());
                    if (!addscheduled) {
                        ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                        return;
                    }
                    aBoolean = true;
                    ReserveActivity.start(split[2], split[1] + "-1");
                }
            } else {
                for (int iq = 0; iq < mlist.size(); iq++) {
                    List<DataInfoBean.DataBean.ListBean> listBeans = mlist.get(iq);
                    for (int is = 0; is < listBeans.size(); is++) {
                        DataInfoBean.DataBean.ListBean listBean = listBeans.get(is);
                        List<DataInfoBean.DataBean.ListBean.OrderBean> order1 = listBean.getOrder();
                        if (order1 != null) {
                            for (int j = 0; j < order1.size(); j++) {
                                DataInfoBean.DataBean.ListBean.OrderBean orderBean = order1.get(j);
                                if (split[0].equals("" + orderBean.getId())) {
                                    if (order1.get(j).getType() == 1) {//潜客
                                        boolean sayall = JurisdictionUtils.getSayall(getContext());
                                        if (sayall) {
                                            SPUtils.put(getContext(), "currentDate", "");
                                            PotentialInformationActivity.start(order1.get(j).getBid() + "", orderBean.getBegin_year() + "", orderBean.getBegin_month() + "", orderBean.getBegin_day() + ""
                                                    , orderBean.getBegin_night() + "",
                                                    orderBean.getBid() + "");
                                        } else {
                                            boolean saypersonal = JurisdictionUtils.getSaypersonal(getContext());
                                            if (saypersonal) {
                                                boolean getuserid = JurisdictionUtils.getuserid(getContext(), order1.get(j).getDirector_id());
                                                if (getuserid) {
                                                    SPUtils.put(getContext(), "currentDate", "");
                                                    PotentialInformationActivity.start(order1.get(j).getBid() + "", orderBean.getBegin_year() + "", orderBean.getBegin_month() + "", orderBean.getBegin_day() + ""
                                                            , orderBean.getBegin_night() + "",
                                                            orderBean.getBid() + "");
                                                }
                                            } else {
                                                ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                                                return;
                                            }
                                        }

                                        return;
                                    } else {//预定
                                        boolean sayall = JurisdictionUtils.getSayall(getContext());
                                        if (sayall) {
                                            SPUtils.put(getContext(), "currentDate", "");
                                            ReserveInformationActivity.start(orderBean.getId() + "", orderBean.getType() + "");
                                            return;
                                        } else {
                                            boolean saypersonal = JurisdictionUtils.getSaypersonal(getContext());
                                            if (saypersonal) {
                                                boolean getuserid = JurisdictionUtils.getuserid(getContext(), order1.get(j).getDirector_id());
                                                if (getuserid) {
                                                    SPUtils.put(getContext(), "currentDate", "");
                                                    ReserveInformationActivity.start(orderBean.getId() + "", orderBean.getType() + "");

                                                }
                                            } else {
                                                ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                                                return;
                                            }
                                        }
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    };

    private View.OnClickListener blockListenernoon = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String xiaokongbiao = SPUtils.get(getContext(), "xiaokongbiao", "").toString();
            if (xiaokongbiao.equals("1")) {
                ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                return;
            }
            String string = view.getTag().toString();
            String[] split = string.split("/");
            Log.e("TAG", "下   " + split[0] + "  " + split[1] + "  " + split[2]);
            if (split[0].equals("NULL")) {
                long l = DatePhotoUtils.dateStamp(split[1]);
                DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date(System.currentTimeMillis());//获取当前时间
                String currentDate = simpleDateFormat.format(date);
                long l1 = DatePhotoUtils.dateStamp(currentDate);
                if (l < l1) {
                    ToastUtils.shortToast(getContext(), "禁止选择之前日期");
                } else {
                    boolean addscheduled = JurisdictionUtils.getAddscheduled(getContext());
                    if (!addscheduled) {
                        ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                        return;
                    }
                    aBoolean = true;
                    ReserveActivity.start(split[2], split[1] + "-2");
                }
            } else {
                for (int iq = 0; iq < mlist.size(); iq++) {
                    List<DataInfoBean.DataBean.ListBean> listBeans = mlist.get(iq);
                    for (int is = 0; is < listBeans.size(); is++) {
                        DataInfoBean.DataBean.ListBean listBean = listBeans.get(is);
                        List<DataInfoBean.DataBean.ListBean.OrderBean> order1 = listBean.getOrder();
                        if (order1 != null) {
                            for (int j = 0; j < order1.size(); j++) {
                                DataInfoBean.DataBean.ListBean.OrderBean orderBean = order1.get(j);
                                if (split[0].equals("" + orderBean.getId())) {
                                    if (order1.get(j).getType() == 1) {//潜客
                                        boolean sayall = JurisdictionUtils.getSayall(getContext());
                                        if (sayall) {
                                            SPUtils.put(getContext(), "currentDate", "");
                                            PotentialInformationActivity.start(order1.get(j).getBid() + "", orderBean.getBegin_year() + "", orderBean.getBegin_month() + "", orderBean.getBegin_day() + ""
                                                    , orderBean.getBegin_night() + "",
                                                    orderBean.getBid() + "");
                                        } else {
                                            boolean saypersonal = JurisdictionUtils.getSaypersonal(getContext());
                                            if (saypersonal) {
                                                boolean getuserid = JurisdictionUtils.getuserid(getContext(), order1.get(j).getDirector_id());
                                                if (getuserid) {
                                                    SPUtils.put(getContext(), "currentDate", "");
                                                    PotentialInformationActivity.start(order1.get(j).getBid() + "", orderBean.getBegin_year() + "",
                                                            orderBean.getBegin_month() + "", orderBean.getBegin_day() + ""
                                                            , orderBean.getBegin_night() + "",
                                                            orderBean.getBid() + "");
                                                }
                                            } else {
                                                ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                                                return;
                                            }
                                        }
                                        return;
                                    } else {//预定
                                        boolean sayall = JurisdictionUtils.getSayall(getContext());
                                        if (sayall) {
                                            SPUtils.put(getContext(), "currentDate", "");
                                            ReserveInformationActivity.start(orderBean.getId() + "", orderBean.getType() + "");
                                            return;
                                        } else {
                                            boolean saypersonal = JurisdictionUtils.getSaypersonal(getContext());
                                            if (saypersonal) {
                                                boolean getuserid = JurisdictionUtils.getuserid(getContext(), order1.get(j).getDirector_id());
                                                if (getuserid) {
                                                    SPUtils.put(getContext(), "currentDate", "");
                                                    ReserveInformationActivity.start(orderBean.getId() + "", orderBean.getType() + "");

                                                }
                                            } else {
                                                ToastUtils.longToast(getContext(), "当前账号没有操作权限哦");
                                                return;
                                            }
                                        }
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    };

    private ExcelPanel.OnScrollListener onScrollListener = new ExcelPanel.OnScrollListener() {
        @Override
        public void onScrolled(ExcelPanel excelPanel, int dx, int dy) {
            super.onScrolled(excelPanel, dx, dy);
            int firstVisibleItemPosition = excelPanel.findFirstVisibleItemPositionLast();
//            int firstVisibleItemPosition1 = excelPanel.findFirstVisibleItemPosition();
            if (firstVisibleItemPosition >= 0) {
                String dateString = rowTitles.get(firstVisibleItemPosition).getDateString();//最后一条可见
                String[] split = dateString.split("-");
//                String dateStrings = rowTitles.get(firstVisibleItemPosition1).getDateString();//第一条可见
//                String[] splits = dateStrings.split("-");
                String y1 = split[0];
                String m1 = split[1];
                String d1 = split[2];


//                y = splits[0];
//                m = splits[1];
//                d = splits[2];
//                Log.d("TAG", "onScrolled: "+y+"-"+m);
                if (!DataList.contains(split[0] + "-" + split[1])) {
                    DataList.add(y1 + "-" + m1);
                    tvMainTime.post(new Runnable() {
                        @Override
                        public void run() {
                            tvMainTime.setText(split[0].trim() + "年" + split[1] + "月");
                        }
                    });
                    ShowData(y1, m1, d1, 3);
                    return;
                } else {
                    String s = split[0].trim() + "年" + split[1] + "月";
                    tvMainTime.post(new Runnable() {
                        @Override
                        public void run() {
                            tvMainTime.setText("" + s);
                        }
                    });
                    return;
                }
            }
        }
    };

    private void initListener() {
        OkHttpUtils.post()
                .url(Api.POST_INDEX_SCHEDULED)
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "宴会厅onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "宴会厅onResponse   " + response);
                        if (response.equals("")) {
                            ShowData(y, m, d, 2);
                            return;
                        }
                        BeanBean beanBean = JsonUtils.parseObject(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            scheduledBean = JsonUtils.parseByGson(response, ScheduledBean.class);
                            for (int i = 0; i < scheduledBean.getData().size(); i++) {
                                tvChoiceHall.setText(scheduledBean.getData().get(0).getName());
                                banquet = scheduledBean.getData().get(0).getId() + "";
                                SPUtils.put(getContext(), "name", scheduledBean.getData().get(0).getName());
                                SPUtils.put(getContext(), "sched_id", scheduledBean.getData().get(0).getId() + "");
                                SPUtils.put(getContext(), "max", scheduledBean.getData().get(0).getMax() + "");
                            }

                            ShowData(y, m, d, 2);
                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(getContext(), "token", "");
                            SPUtils.put(getContext(), "id", "");
                            Intent intent = new Intent(getContext(), LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }
                });
        tvChoiceHall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showChoiceHallDialog(view);
            }
        });
        tvMainHotel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // showHotelDialog(view);
            }
        });
        boolean notenabled = JurisdictionUtils.getNotenabled(getContext());
        if (notenabled) {
            textZero.setVisibility(View.GONE);
        } else {
            textZero.setVisibility(View.VISIBLE);
        }
        textZero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String xiaokongbiao = SPUtils.get(getContext(), "xiaokongbiao", "").toString();
                if (xiaokongbiao.equals("1")) {
                    ToastUtils.shortToast(getContext(), "前账号没有操作权限哦");
                    return;
                }

                ZeroPointActivity.start();
            }
        });
        tvMainTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CalendarActivity.start(3);
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this); //解除注册
        }
        aBoolean = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);  //事件的注册
        }
        if (aBoolean) {
            String string1 = SPUtils.get(getContext(), "currentDate", "").toString();
            if (!string1.equals("")) {
                String[] two = string1.split("-");
                tvMainTime.setText(two[0] + "年" + two[1] + "月");
                y = two[0];
                m = two[1];
                d = two[2];
                mlist.clear();
                ShowData(y, m, d, 6);
            }
            aBoolean = false;
        }

    }

    private void showChoiceHallDialog(View view) {
        if (scheduledBean != null&& scheduledBean.getCode().equals("0")  ) {
            if (scheduledBean.getData().size() == 0) {
                return;
            }
            new HallListDialog.Builder(getActivity()).setList(scheduledBean.getData()).setOnListener(new HallListDialog.OnListener() {
                @Override
                public void onSelected(BasePopupWindow popupWindow, int position) {
                    tvChoiceHall.setText(scheduledBean.getData().get(position).getName());
                    banquet = scheduledBean.getData().get(position).getId() + "";
                    SPUtils.put(getContext(), "name", scheduledBean.getData().get(position).getName());
                    SPUtils.put(getContext(), "sched_id", scheduledBean.getData().get(position).getId() + "");
                    SPUtils.put(getContext(), "max", scheduledBean.getData().get(position).getMax());
                    String replace = tvMainTime.getText().toString().replace("年", "-").replace("月", "-");
                    String[] two = replace.split("-");
                    y = two[0];
                    m = two[1];
                    ShowData(y, m, d, 5);
                }
            }).showAsDropDown(view);
        }
    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        aBoolean = false;
        if (carrier != null) {
            if (carrier.getStarttime() == null) {
                return;
            }
            long l = DatePhotoUtils.dateStamp(carrier.getStarttime().replace("-", "-"));
            DateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月");
            Date date = new Date(l);//获取当前时间
            String currentDate = simpleDateFormat.format(date);
            tvMainTime.setText("" + currentDate);
            String[] two = carrier.getStarttime().split("-");
            y = two[0];
            m = two[1];
            d = two[2];
            SPUtils.put(getContext(), "currentDate", y+"-"+m+"-"+d);
            ShowData(two[0], two[1], two[2], 4);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);  //事件的注册
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        aBoolean = false;
        SPUtils.put(getContext(), "aBoolean", "2");
        if (hidden) {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this); //解除注册
            }
        } else {
            String string1 = SPUtils.get(getContext(), "currentDate", "").toString();
            if (!string1.equals("")) {
                String[] two = string1.split("-");
                tvMainTime.setText(two[0] + "年" + two[1] + "月");
                y = two[0];
                m = two[1];
                d = two[2];
                ShowData(y, m, d, 6);
                if (!EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().register(this);  //事件的注册
                }
            }else{
                ShowData(y, m, d, 6);
                if (!EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().register(this);  //事件的注册
                }
            }

        }
    }

    @Override
    public void onLoadMore() {

        if (!isLoading) {
//            isLoading=true;
//            SPUtils.put(getContext(), "homeorder",  "#-#-#-#-#");
            loadData(moreStartTime, false);
//            String[] split = tvMainTime.getText().toString().replace("年", "-").replace("月", "-").split("-");
//            int i=Integer.valueOf(split[0]);
//            int j;
//            if(split[1].equals("10")){
//                j=Integer.valueOf(split[1]);
//            }else{
//                j=Integer.valueOf(split[1].replace("0", ""));
//            }
//            if(j==12){
//               i=i+1;
//                j=1;
//            }else{
//                j=j+1;
//            }
//            PAGE_SIZE= DatePhotoUtils.getMonthOfDay(i,j);
//            if(j<10){
//                y =i+"";
//                m="0"+j;
//                d="01";
//                ShowData(i+"", "0"+j, "01", 6);
//            }else{
//                y =i+"";
//                m=""+j;
//                d="01";
//                ShowData(i+"", ""+j, "01", 6);
//            }
//            tvMainTime.setText(y+"年"+m+"月");

        }
    }

    @Override
    public void onLoadHistory() {
        if (!isLoading) {
//            isLoading=true;
//            SPUtils.put(getContext(), "homeorder",  "#-#-#-#-#");
//            String[] split = tvMainTime.getText().toString().replace("年", "-").replace("月", "-").split("-");
//            int i=Integer.valueOf(split[0]);
//            int j;
//            if(split[1].equals("10")){
//                j=Integer.valueOf(split[1]);
//            }else{
//                j=Integer.valueOf(split[1].replace("0", ""));
//            }
//            if(j==1){
//                i=i-1;
//                j=12;
//            }else{
//                j=j-1;
//            }
//            PAGE_SIZE= DatePhotoUtils.getMonthOfDay(i,j);
//            if(j<10){
//                y =i+"";
//                m="0"+j;
//                d="01";
//                ShowData(i+"", "0"+j, "01", 6);
//            }else{
//                y =i+"";
//                m=""+j;
//                d="01";
//                ShowData(i+"", ""+j, "01", 6);
//            }
//            tvMainTime.setText(y+"年"+m+"月");
            loadData(historyStartTime, true);
        }
    }

    private List<RowTitle> genRowData(long startTime) {
        List<RowTitle> rowTitles = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < PAGE_SIZE; i++) {
            RowTitle rowTitle = new RowTitle();
            rowTitle.setAvailableRoomCount(random.nextInt(10) + 10);
            rowTitle.setDateString(dateFormatPattern.format(startTime + i * ONE_DAY));
            rowTitle.setWeekString(weekFormatPattern.format(startTime + i * ONE_DAY));
            rowTitles.add(rowTitle);
        }
        return rowTitles;
    }

    private List<ColTitle> genColData() {
        List<ColTitle> colTitles = new ArrayList<>();
        if (list != null || list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                DataInfoBean.DataBean.ListBean listBean = list.get(i);
                ColTitle colTitle = new ColTitle();
                colTitle.setRoomNumber(listBean.getName());
                colTitle.setId("" + listBean.getId());
                colTitles.add(colTitle);
            }
        } else {
            for (int i = 0; i < ROW_SIZE; i++) {
                ColTitle colTitle = new ColTitle();
                colTitle.setRoomNumber(i + "号");
                colTitle.setId("");
                colTitles.add(colTitle);
            }
        }

        return colTitles;
    }

    private List<List<Cell>> genCellData() {
        List<List<Cell>> cells = new ArrayList<>();
        for (int i = 0; i < ROW_SIZE; i++) {
            List<Cell> cellList = new ArrayList<>();
            cells.add(cellList);
            for (int j = 0; j < 30; j++) {
                Cell cell = new Cell();
                Random random = new Random();
                int number = random.nextInt(9);
                if (number == 1 || number == 2 || number == 3) {
                    cell.setStatus(number);
                    cell.setChannelName("");
                    cell.setBookingName("");
                } else {
                    cell.setStatus(0);
                }
                cellList.add(cell);
            }
        }
        return cells;
    }


    MainActivity.MyTouchListener myTouchListener = new MainActivity.MyTouchListener() {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            //处理手势事件（根据个人需要去返回和逻辑的处理）
            int pointerCount = event.getPointerCount(); // 获得多少点
            if (pointerCount > 1) {// 多点触控，
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_POINTER_2_UP://第二个手指抬起的时候
                        break;
                    default:
                        break;
                }
                return mScaleGestureDetector.onTouchEvent(event);//让mScaleGestureDetector处理触摸事件
            }
            return false;
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ((MainActivity) this.getActivity()).unRegisterMyTouchListener(myTouchListener);
    }

    public class ScaleGestureListener implements
            ScaleGestureDetector.OnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float previousSpan = detector.getPreviousSpan();// 前一次双指间距
            float currentSpan = detector.getCurrentSpan();// 本次双指间距
            int width = whList.get(0).getWeekWidth();
            int height = whList.get(0).getWeekHeight();
            int weekSize = whList.get(0).getWeekSize();

            int rootwidth = whList.get(0).getRootwidth();
            int rootheight = whList.get(0).getRootheight();
            int rootSize = whList.get(0).getRootSize();

            int containerheight = whList.get(0).getContainerheight();
            int containerwidth = whList.get(0).getContainerwidth();
            int pmsheight = whList.get(0).getPmsheight();
            int pmswidth = whList.get(0).getPmswidth();
            int textSize = whList.get(0).getTextSize();
            int blow = whList.get(0).getBlow();
            if (currentSpan < previousSpan) {
                // 缩小
                scale = preScale - (previousSpan - currentSpan) / 1000;
                if (width >= (157 - 20)) {
                    whList.clear();
                    WHBean whBean = new WHBean();
                    whBean.setWeekWidth(width - 5);
                    whBean.setWeekHeight(height - 5);
                    whBean.setWeekSize(weekSize - 5);
                    whBean.setRootwidth(rootwidth - 5);
                    whBean.setRootheight(rootheight - 5);
                    whBean.setRootSize(rootSize - 1);
                    whBean.setContainerwidth(containerwidth - 5);
                    whBean.setContainerheight(containerheight - 5);
                    whBean.setPmsheight(pmsheight - 5);
                    whBean.setPmswidth(pmswidth - 5);
                    whBean.setTextSize(textSize - 1);
                    whBean.setBlow(blow - 1);
                    leftCellWidth = leftCellWidth - 5;
                    topCellHeight = topCellHeight - 5;
                    normalCellWidth = normalCellWidth - 5;
                    excelPanel.setLeftCellWidth(leftCellWidth, topCellHeight, normalCellWidth);
                    whList.add(whBean);
                    adapter.setSf(whList, 2);
                }
            } else {
                // 放大
                scale = preScale + (currentSpan - previousSpan) / 1000;
                if (width <= (157 + 20)) {
                    whList.clear();
                    WHBean whBean = new WHBean();
                    whBean.setWeekWidth(width + 5);
                    whBean.setWeekHeight(height + 5);
                    whBean.setWeekSize(weekSize + 5);
                    whBean.setRootwidth(rootwidth + 5);
                    whBean.setRootheight(rootheight + 5);
                    whBean.setRootSize(rootSize + 1);
                    whBean.setContainerwidth(containerwidth + 5);
                    whBean.setContainerheight(containerheight + 5);
                    whBean.setPmsheight(pmsheight + 5);
                    whBean.setPmswidth(pmswidth + 5);
                    whBean.setTextSize(textSize + 1);
                    whBean.setBlow(blow + 1);
                    leftCellWidth = leftCellWidth + 5;
                    topCellHeight = topCellHeight + 5;
                    normalCellWidth = normalCellWidth + 5;
                    excelPanel.setLeftCellWidth(leftCellWidth, topCellHeight, normalCellWidth);
                    whList.add(whBean);
                    adapter.setSf(whList, 2);
                }
            }
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            // 一定要返回true才会进入onScale()这个函数
            Log.e("TAG", "2");
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            preScale = scale;// 记录本次缩放比例
            // ShowData(y, m, d, 6);
        }
    }
}